package com.teamclub.erp.sservices

import io.ebean.{Ebean, ExpressionList}
import com.teamclub.domain.erp.storage.StorageInfo
import com.teamclub.erp.sforms.StorageInfoForm
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.F
import com.teamclub.util.page.Pager
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.util.List

import org.springframework.beans.BeanUtils
/**
  * Created by ilkkzm on 17-9-11.
  */
@Service
class StorageInfoService {
  val logger = LoggerFactory.getLogger(classOf[StorageInfoService])
  def expr(where: ExpressionList[StorageInfo], form: StorageInfoForm): Unit = {
    if(StringUtils.isNotBlank(form.getOrganNo)) {
      where.eq("organNo", form.getOrganNo)
    }
    if(StringUtils.isNotBlank(form.storageName)) {
      where.like("storageName", '%' + form.storageName + '%')
    }
  }
  def list(form: StorageInfoForm): F.Either[List[StorageInfo], ErrorCode] = {
    var where = Ebean.find(classOf[StorageInfo]).where()
    expr(where, form)
    F.Either.Left(where.findList())
  }

  def backList(form : StorageInfoForm): F.Either[Pager[StorageInfo], ErrorCode] = {
    var where = Ebean.find(classOf[StorageInfo]).where()
    expr(where, form)
    F.Either.Left(Pager.genePager(where.query(), form))
  }

  def add(form: StorageInfoForm): F.Either[StorageInfo, ErrorCode] = {
    var instance = new StorageInfo
    if(form.id != null) {
      instance = Ebean.find(classOf[StorageInfo], form.id)
    }
    BeanUtils.copyProperties(form, instance)
    if(form.id != null) {
      instance.update()
    } else {
      instance.save()
    }
    F.Either.Left(instance)
  }
}
